package com.rentalcar.wechat.service.impl;


import cn.hutool.core.util.IdUtil;
import com.alipay.api.domain.OrderItem;
import com.rentalcar.common.exception.ServiceException;
import com.rentalcar.wechat.domain.UmsCarInfo;
import com.rentalcar.wechat.domain.UmsMember;
import com.rentalcar.wechat.domain.UmsRentalOrder;
import com.rentalcar.wechat.service.IUmsCarInfoService;
import com.rentalcar.wechat.service.IUmsMemberService;
import com.rentalcar.wechat.service.IUmsRentalOrderService;
import com.rentalcar.wechat.service.OrderServiceApi;
import com.rentalcar.wechat.vo.CancelOrderParams;
import com.rentalcar.wechat.vo.ConfirmOrderParams;
import com.rentalcar.wechat.vo.SubmitOrderParams;
import com.rentalcar.wechat.vo.SubmitOrderResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by 魔金商城 on 17/11/7.
 * 订单服务接口
 */
@Service
@Slf4j
public class OrderServiceApiImpl implements OrderServiceApi {

    /**
     * 注入订单服务接口
     */
    @Autowired
    private IUmsRentalOrderService orderService;
    @Autowired
    private IUmsCarInfoService umsCarInfoService;
    @Autowired
    private IUmsMemberService umsMemberService;
    /**
     * 订单状态map
     */
    private static final Map<String, String> statusMap = new HashMap<>();

    static {
        statusMap.put("1", "待付款");
        statusMap.put("2", "已付款");
        statusMap.put("3", "已完成");
        statusMap.put("4", "已取消");
        statusMap.put("5", "退款通过");
    }

    /**
     * 调试日志
     */
    private Logger logger = LoggerFactory.getLogger(OrderServiceApiImpl.class);


    @Override
    public SubmitOrderResponse submitOrder(SubmitOrderParams submitOrderParams) {
        if (Objects.isNull(submitOrderParams)) {
            log.info("submitOrder fail due to params is empty....");
            return SubmitOrderResponse.buildFail("R-0000011");
        }
        log.info("submitOrder and submitOrderParams :{}", submitOrderParams);
        //获取订单信息
        //订单类型 0 充值 1 月会员 2 季会员 3 年会员 4 爵位 5 皮肤 6 礼物 7 钻石
        UmsRentalOrder omsOrder = getOrderDetail(submitOrderParams);

        //return SubmitOrderResponse.buildNeedPayResponse(omsOrder.getOrderCode(), omsOrder.getPrice());
        // 返回订单信息
        return getSubmitOrderResponse(omsOrder);
    }


    @Override
    public int cancleOrder(CancelOrderParams cancelOrderParams) {
        logger.debug("cancleOrder and  cancelOrderParams {}", cancelOrderParams);

        if (Objects.isNull(cancelOrderParams)) {
            logger.error("cancleOrder fail due to cancelOrderParams is null...");
            return 0;
        }

        // 查询订单信息
        UmsRentalOrder order = this.queryOrderDetailById(cancelOrderParams.getOrderId(), cancelOrderParams.getCustomerId());

        // 没有查询到订单返回错误
        if (Objects.isNull(order)) {
            logger.error("cancleOrder fail  due to order is not exist");
            return -1;
        }


        // 如果订单来自前端  并且订单的会员id和用户的会员id不一致 则直接返回
        if (cancelOrderParams.isFromCustomer() && cancelOrderParams.getCustomerId() != order.getUserId()) {
            logger.error("cancleOrder fail due to order customerId is not match...");
            return -2;
        }

        // 取消订单失败
        if (orderService.cancelOrder(cancelOrderParams.getOrderId(), cancelOrderParams.getStoreId(), cancelOrderParams.getReason()) == 0) {
            logger.error("cancleOrder fail....");
            return 0;
        }

        return 1;
    }

    @Override
    public int confirmOrderPayed(ConfirmOrderParams confirmOrderParams) {
        log.info("confirmOrderPayed and confirmOrderParams:{}", confirmOrderParams);

        if (Objects.isNull(confirmOrderParams)) {
            log.error("confirmOrderPayed fail due to confirmOrderParams is null...");
            return 0;
        }

        // 修改结果
        int result = 0;

        // 请求来源前端用户
        if (confirmOrderParams.isFromCustomer()) {
            result = orderService.updateOrderPayed(confirmOrderParams.getOrderCode(), confirmOrderParams.getCustomerId(), confirmOrderParams.getIsPredepositPay(), confirmOrderParams.getTransCode(), confirmOrderParams.getChannel());
        }

        // 修改失败
        if (result == 0) {
            log.error("confirmOrderPayed faill...");
            throw new ServiceException("update orderfail....");
        }

        return 1;
    }

    @Override
    public int buyAgain(long orderId, long customerId) {
        return 0;
    }

    @Override
    public UmsRentalOrder queryOrderDetailById(long id, long customerId, OrderItem... orderItems) {
        return null;
    }

    @Override
    public void saveOrders(List<UmsRentalOrder> orders, boolean needCheckShoppingCartDelNum) {

    }

    @Override
    public int autoCancelOrder() {
        return 0;
    }

    /**
     * 获得订单返回信息
     *
     * @param omsOrder 订单信息
     * @return 返回订单信息
     */
    private SubmitOrderResponse getSubmitOrderResponse(UmsRentalOrder omsOrder) {
        String payType = omsOrder.getPayType();
        if ("1".equals(payType)) {
            //不需要支付
            UmsMember userMember = umsMemberService.queryCustomerInfoById(omsOrder.getUserId());
            //更新用户金额
            orderService.updateUmsRentalOrder(omsOrder);
            return SubmitOrderResponse.buildNoNeedPayResponse(omsOrder.getTotalAmount(), omsOrder.getOrderCode());
        } else {
            // 有需要付款的订单 则返回需要付款的实体  注意 订单号拿的的主订单号
            orderService.insertUmsRentalOrder(omsOrder);
            return SubmitOrderResponse.buildNeedPayResponse(omsOrder.getOrderCode(), omsOrder.getTotalAmount());

        }

    }

    /**
     * 获得订单的详细信息
     *
     * @param submitOrderParams 提交订单的参数
     * @return 返回订单详情
     */
    private UmsRentalOrder getOrderDetail(SubmitOrderParams submitOrderParams) {
        UmsCarInfo umsCarInfo = umsCarInfoService.selectUmsCarInfoById(submitOrderParams.getCarId());

        // 生成订单
        UmsRentalOrder order = new UmsRentalOrder();
        // 设置订单的用户id
        order.setUserId(submitOrderParams.getCustomerId());

        // 设置订单号
        order.setOrderCode(IdUtil.getSnowflakeNextIdStr());

        // 设置订单类型 OrderType
        order.setOrderType(submitOrderParams.getOrderType());

        // 订单的原始价格(每个单品详情页面的价格) OriginTotalPrice
        order.setOriginTotalPrice(submitOrderParams.getOriginTotalPrice());
        //手续费
        order.setHandlingFee(submitOrderParams.getHandlingFee());

        // 订单的最终价格
        order.setTotalAmount(submitOrderParams.getTotalPrice());

        //总的优惠价格
        order.setTotalPrice(submitOrderParams.getTotalPrice());

        // 设置支付方式
        order.setPayType(submitOrderParams.getPayType());

        //设置订单状态
        order.setOrderStatus("0");

        BeanUtils.copyProperties(umsCarInfo, order);

        // 订单来源
        order.setSource(submitOrderParams.getSource());
        return order;
    }
}
